package com.music.lib.qianqian;

import com.lcx.annotation.IOCValue;
import com.lcx.util.JsonHandler;
import com.lcx.util.StringUtil;
import com.music.lib.MusicLib;
import com.music.lib.qianqian.support.Document;
import com.music.lib.qianqian.support.Element;
import com.music.lib.qianqian.support.Elements;
import com.music.lib.qianqian.support.Jsoup;
import com.music.util.HttpClient;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author comp
 * @version V1.0.0
 * @ProjectName: My-Utils
 * @Package com.music.lib.qianqian
 * @ClassName: QianQianMusicLibImpl
 * @Description:
 * @date 2018年09月17日  上午  16:03
 */
@IOCValue
public class QianQianMusicLibImpl implements MusicLib {
    @Override
    public String getLibName() {
        return "千千音乐网页库";
    }

    @Override
    public int getDefaultPageSize() {
        return 20;
    }

    //http://music.taihe.com/search/song?s=1&key=%E9%82%A3%E4%B8%80%E5%B9%B4&jump=0&start=0&size=20&third_type=0
    @Override
    public List<MusicInfo> getMusicInfo(Map<String, Object> param) {
        HttpClient.clearAll();
        String name = (String) param.get("name");
        if(name == null) return null;
        Integer page = (int) param.get("page");
        if(page == null) page = 1;
        Integer pageSize = (int)param.get("pageSize");
        if(pageSize == null) pageSize = 20;
        try {
            name = URLEncoder.encode(name,"UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        List<MusicInfo> listMusics = new ArrayList<>();
        try{
            //http://music.taihe.com/search/song?s=1&key=%E9%82%A3%E4%B8%80%E5%B9%B4&jump=0&start=0&size=20&third_type=0
            String requestUrl = "http://music.taihe.com/search/song?s=1&key="+name+"&jump=0&start="+((page-1)*20)+"&size="+pageSize+"&third_type=0";
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String result = null;
            HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
            try {
                HttpClient.request(requestUrl,null,bos);
                result = new String(bos.toByteArray(),"UTF-8");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            Document document = Jsoup.parse(result);
            Elements elements = document.select("#result_container ul>li");
            if(elements!=null){
                MusicInfo musicInfo;
                Map<String,Object> otherInfo;
                for(Element e:elements){
                    otherInfo = new HashMap<>();
                    musicInfo = new MusicInfo();
                    musicInfo.setOtherInfo(otherInfo);
                    String jsonInfo = e.attr("data-songitem");
                    if(StringUtil.isNull(jsonInfo)){
                        continue;
                    }
                    Map<String,Object> info = JsonHandler.parseJson(jsonInfo);
                    Map<String,Object> item = (Map<String, Object>) info.get("songItem");
                    if(item == null) continue;
                    String id = item.get("sid").toString();
                    otherInfo.put("albumId",id);
                    Element title = e.select(".song-title").first();
                    Element singer = e.select(".singer").first();
                    Element album = e.select(".album-title").first();
                    if(title == null) continue;
                    if(title != null){
                        if(StringUtil.isNull(title.text())) continue;
                        musicInfo.setName(title.text());
                    }
                    if(album != null){
                        otherInfo.put("albumName",album.text());
                    }
                    if(singer!=null){
                        otherInfo.put("author",singer.text());
                        otherInfo.put("displayName",singer.text()+" - "+musicInfo.getName());
                    }
                    musicInfo.setType("mp3");
                    listMusics.add(musicInfo);
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return listMusics;
    }

    @Override
    public boolean supportSplitPage() {
        return true;
    }

    @Override
    public MusicInfo getDetail(MusicInfo musicInfo) {
        //获取播放地址
        //http://play.taihe.com/data/music/songlink
        //获取音乐封面
        //http://play.taihe.com/data/music/songinfo
        Map<String,Object> otherInfo = musicInfo.getOtherInfo();
        String id = (String) otherInfo.get("albumId");
        HttpClient.clearAll();
        HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
        HttpClient.addProperty("songIds",id);
        HttpClient.setRequestMethod("POST");
        String result = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            HttpClient.request("http://play.taihe.com/data/music/songinfo",null,bos);
            result = new String(bos.toByteArray(),"UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String,Object> infoResult = JsonHandler.parseJson(result);
        List<Map<String,Object>> infos = (List<Map<String, Object>>) ((Map<String,Object>)infoResult.get("data")).get("songList");
        Map<String,Object> info = infos.get(0);
        String picUrl = (String) info.getOrDefault("songPicRadio",info.getOrDefault("songPicBig",info.get("songPicSmall")));
        otherInfo.put("img",picUrl);

        HttpClient.clearAll();
        HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
        HttpClient.addProperty("songIds",id);
        HttpClient.addProperty("hq","0");
        HttpClient.addProperty("type","mp3");
        HttpClient.addProperty("pt","0");
        HttpClient.setRequestMethod("POST");
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            HttpClient.request("http://play.taihe.com/data/music/songlink",null,bos);
            result = new String(bos.toByteArray(),"UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        infoResult = JsonHandler.parseJson(result);
        infos = (List<Map<String, Object>>) ((Map<String,Object>)infoResult.get("data")).get("songList");
        info = infos.get(0);
        String url = (String) info.getOrDefault("songLink",info.get("showLink"));
        String lrcUrl = (String)info.get("lrcLink");
        musicInfo.setUrl(url);
        if(StringUtil.isNotNull(lrcUrl)){
            HttpClient.clearAll();
            HttpClient.setRequestMethod("GET");
            HttpClient.addHead(HttpClient.HEAD_USER_AGENT,HttpClient.AGENT_CHROME_HEAD);
            try{
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                HttpClient.request(lrcUrl,null,bos);
                String lrc = new String(bos.toByteArray(),"UTF-8");
                musicInfo.setLrc(lrc);
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        return musicInfo;
    }
}
